package com.samoiloff.ui.list.smart.controller {
	import com.samoiloff.framework.controller.AbstractController;
	import com.samoiloff.ui.list.smart.interfaces.CellRenderer;
	import com.samoiloff.ui.list.smart.model.SmartListModel;
	import com.samoiloff.ui.list.smart.view.SmartListRenderers;
	import com.samoiloff.ui.list.smart.view.SmartListView;
	import com.samoiloff.ui.list.smart.view.SmartListViewport;

	import flash.events.Event;

	/**
	 * @author Samoiloff
	 */
	public class SmartListViewportController extends AbstractController {
		
		private var _vModel	: SmartListModel;		
		private var _vView	: SmartListView;
		private var _viewport: SmartListViewport;
		private var _renderers:SmartListRenderers;
		
		public function SmartListViewportController(model: SmartListModel) {
			super(model);
			
			_vModel = model;
			_vView = _vModel.view;
			_viewport = _vView.viewport;
			_renderers = _vView.renderers;
			
			_vModel.mainMc.addChild(_viewport.mc);
			
			_vModel.addEventListener(Event.RESIZE, onResize);
			_vView.scroll.addEventListener(Event.SCROLL, onScroll);
			
			_vModel.addEventListener(SmartListModel.DATA_PROVIDER_CHANGED, onDataProviderChanged);
			
			onResize();
		}

		private function onDataProviderChanged(event: Event): void {
			onScroll();
		}

		private function onResize(event: Event = null): void {
			_viewport.width = _vModel.width - _vView.scroll.width;
			_viewport.height = _vModel.height;
			onScroll();
		}

		private function onScroll(e:Event = null): void {
			_vView.viewport.y = _vView.scroll.scrollPosition;
			
			var minY:Number = _vView.viewport.y;
			var maxY:Number = _vView.viewport.y + _vView.viewport.height;
			
			var i:int;
			var cellMaxY:Number;
			var cellRenderer:CellRenderer;
			
			for (i = _viewport.length-1;i >=0; i--) {
				cellRenderer = _viewport.getItemAt(i);
				cellMaxY = cellRenderer.bounds.y + cellRenderer.bounds.height;
				if (cellRenderer.bounds.height > maxY || cellMaxY < minY) {
					_viewport.removeItem(cellRenderer);
				}
			}
			
			//TODO: optimize add logic
			for (i = 0; i<_renderers.length; i++) {
				cellRenderer = _renderers.getItemAt(i);
				cellMaxY = cellRenderer.bounds.y + cellRenderer.bounds.height;
				if (cellRenderer.bounds.y < maxY) {
					if (cellMaxY > minY) {
						if (!cellRenderer.visible) {
							_viewport.addItem(cellRenderer);
						}
					}
				}
			}
		}
	}
}
